/*select_client.c 2011.9.2 by yyg*/  
#include <stdio.h>  
#include <stdlib.h>  
#include <errno.h>  
#include <string.h>  
#include <sys/types.h> 
#include <sys/stat.h>
#include <fcntl.h>
#include <netinet/in.h>  
#include <sys/socket.h>  
#include <sys/wait.h>  
#include <pthread.h>  
#include <sys/time.h>  
#include <arpa/inet.h>  
#include <unistd.h>  
#include <resolv.h>  

#include"cltnet.h"

#define MAXBUF 4096

int dbd_send_string(int sockfd, char *string){
	char buffer[MAXBUF];
	int len = 0;
	if(string == NULL) {
		return -1;
	}
	
	len = write(sockfd, string, strlen(string));
	if(len < 0){
		return len;
	}

    len = read(sockfd, buffer, MAXBUF );
	if(strncasecmp(buffer, "copy", 4)!=0){
		return -1;
	}
	return 0;
}

int dbd_send_compile_argv(const struct dbd_hostdef *host ,const char *argv){  
    int sockfd, objfd, ret, retval = 0;
    struct sockaddr_in dest;  
    fd_set rfds;  
	char buffer[MAXBUF], objfile[MAXBUF], *p;
 	
	dbd_get_target_obj(argv, objfile);
	printf("obj file %s\n", objfile);
    //create socket  
    if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0){  
        fprintf(stderr, "Can not create socket\n");  
        retval = errno;
		goto error_out;
    }  
 
    bzero(&dest,sizeof(dest));  
    dest.sin_family = AF_INET;  
    dest.sin_port = htons(host->port);  
    if(inet_aton(host->ip,(struct in_addr *)&dest.sin_addr.s_addr) == 0){  
        fprintf(stderr, "Can not connected to client socket\n");  
        retval = errno;
		goto error_out;
    }  
  
    /*conect to the server*/  
    if(connect(sockfd,(struct sockaddr*)&dest,sizeof(dest)) !=0){  
        fprintf(stderr, "Can not connected to client socket\n");  
        retval = errno;
		goto error_out;
    }  
    
	printf("connected to sever\n"); 
	//set pwd for argv
	p = getcwd(buffer, MAXBUF);
	if(p!=NULL) {p[strlen(p)+1]=0;p[strlen(p)]='/';}
	if( ret = dbd_send_string(sockfd, p) < 0){
		fprintf(stderr, "failed to send pwd\n");
        retval = -1;
		goto error_out;
	}

	if(ret = dbd_send_string(sockfd, argv) < 0){
		fprintf(stderr, "failed to send compile argv\n");
        retval = -1;
		goto error_out;
	}
	
	objfd = open(objfile, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);

	while(ret = read(sockfd, buffer, MAXBUF) > 0){
		if(strcmp(buffer, "bye") != 0)
			ret = write(objfd, buffer, ret);
		else ret = -1;
		if(ret < 0) {
			fprintf(stderr, "failed to receive obj file\n");
        	retval = -1;
			goto error_out;
		}
  		bzero(buffer,MAXBUF+1);  
   	} 
  	
	if(ret < 0) {
		fprintf(stderr, "faild to receive obj file\n");
		retval = -1;
	}
error_out:
	close(objfd);
	close(sockfd);  
    return retval;  
}  
